package com.jingtai.core.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.jingtai.core.config.qinui.QiniuConfig;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @Describe 七牛云上传
 *
 * @Author dianWei
 * @date 2020/11/26 0026
 */
@Slf4j
@Service
public class UploadPictureUtils {

    @Resource
    private QiniuConfig qiniuConfig;

    private static final Configuration cfg = new Configuration(Region.autoRegion());

    private static final UploadManager uploadManager = new UploadManager(cfg);

    private static Auth auth;
    @PostConstruct
    public void init(){
        auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
    }

    public String upload(MultipartFile file) throws IOException {
        String token = auth.uploadToken(qiniuConfig.getBucket());
        String key =DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_FORMAT)+
                UUID.randomUUID().toString().replaceAll("-", "").substring(0,4) + ".jpg";
        FileInputStream inputStream = (FileInputStream) file.getInputStream();
        Response response = uploadManager.put(inputStream, key, token, null, null);
        log.info("{}",response.isOK());
        if (response.isOK()) {
            return qiniuConfig.getDomainName() + "/" + key;
        } else {
            return null;
        }
    }
}